package cn.edu.zut.soft.graduate.log;

import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import org.apache.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author cc
 * @Date 2016/11/28
 * @value 1.0
 */
@Component
public class LoginPathServiceImpl implements LogService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String logString = "id:{},name:{},role:{},loginMode:{},ip:{},uri:{}";

    public void behaviour(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Map map){
        LoginVO loginVO = getLogin(httpRequest);
        logger.info(logString, new Object[]{loginVO.getId(), loginVO.getName(), loginVO.getRole(), loginVO.getLoginMode().name(), getIpAddr(httpRequest), getUri(httpRequest)});
    }

    @Override
    public HttpSession getSession(HttpServletRequest httpRequest) {
        return httpRequest.getSession();
    }


    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private LoginVO getLogin(HttpServletRequest request){
        return (LoginVO) getSession(request).getAttribute(IKEY.USER);
    }

    private String getUri(HttpServletRequest request){
        return request.getRequestURI();
    }
}
